package org.idea.qiyu.live.framework.redis.starter.key.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;

/**
 * 我们希望只加载一个keyBuilder
 */
public class RedisKeyLoadMatch implements Condition {

    private final static Logger LOGGER = LoggerFactory.getLogger(RedisKeyLoadMatch.class);

    private static final String PREFIX = "qiyulive";

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        // 得到当前的上下文对象的域对象
        String curApplicationName = context.getEnvironment().getProperty("spring.application.name");
        if(curApplicationName == null) {
            LOGGER.error("没有匹配到应用名称，所以无法加载任何RedisKeyBuilder对象");
            return false;
        }
        try {
            // 得到正在加载的类->看是否要加载这个类[otherCacheKeyProvider,UserProviderCacheKeyProvider]
            Field classNameField = metadata.getClass().getDeclaredField("className");
            classNameField.setAccessible(true);
            // 去掉.
            //org.idea.qiyu.live.framework.redis.starter.key.OtherCacheKeyBuilder
            String keyBuilderName = (String) classNameField.get(metadata);
            List<String> strings = Arrays.asList(keyBuilderName.split("\\."));
            //[org,idea,qiyu,live,.....,OtherCacheKeyBuilder]
            // 我们需要得到最后一个类名->得到当前的类名
            keyBuilderName = PREFIX + strings.get(strings.size() - 1).toLowerCase();
            boolean matches = keyBuilderName.contains(curApplicationName.replace("-", "").toLowerCase());
            return matches;
        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}